package com.jieyun.rbac.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import com.jieyun.core.utils.ServerResponse;
import com.jieyun.rbac.service.IndexService;
import com.jieyun.rbac.utils.MD5Utils;

/**
 * 关于首页登录注销等方法的服务
 * @author trek
 *
 */
@Service
public class IndexServiceImpl implements IndexService {
	
	/**
	 * 登录服务
	 */
	@Override
	public ServerResponse login(String username, String password) {
		
		if(StringUtils.isBlank(username)) {
			return ServerResponse.fail("账号不能为空");
		}
		if(StringUtils.isBlank(password)) {
			return ServerResponse.fail("密码不能为空");
		}
		
		// login
		Subject subject = SecurityUtils.getSubject();
		password = MD5Utils.encode(password);
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		try {
			subject.login(token);	
		}catch (IncorrectCredentialsException  | UnknownAccountException e) {
			return ServerResponse.fail("账号或者密码不正确");
		}catch(LockedAccountException e) {
			return ServerResponse.fail("账号被冻结,请联系管理员.");
		}catch(Exception e) {
			return ServerResponse.fail("登录失败,请联系管理员.");
		}
		return ServerResponse.ok();
	}

}
